using System.Collections;
using UnityEngine;

public class MonsterSpawner : MonoBehaviour
{
    [SerializeField] private GameObject skeletonPrefab; // 引用小骷髅预制体
    [SerializeField] private float spawnInterval = 3f;  // 每隔几秒生成一次
    [SerializeField] private float spawnDistance = 15f; // 在玩家多远以外生成

    private Transform playerTransform;

    void Start()
    {
        playerTransform = FindObjectOfType<PlayerMovement>().transform;
        StartCoroutine(SpawnMonstersRoutine());
    }

    private IEnumerator SpawnMonstersRoutine()
    {
        // 游戏不结束就一直生成
        while (true) 
        {
            yield return new WaitForSeconds(spawnInterval);
            SpawnMonster();
        }
    }

    private void SpawnMonster()
    {
        // 随机一个方向
        Vector2 randomDirection = Random.insideUnitCircle.normalized;
        // 计算出生点位置（在玩家周围的一个圆圈上）
        Vector3 spawnPosition = playerTransform.position + (Vector3)randomDirection * spawnDistance;

        // 确保怪物在摄像机视野之外 (这是一个简化的检查)
        // 避免怪物突然在屏幕内出现
        if (!IsPositionInCameraView(spawnPosition))
        {
            Instantiate(skeletonPrefab, spawnPosition, Quaternion.identity);
        }
        else
        {
            // 如果随机点在视野内，就反向再生成一次
            spawnPosition = playerTransform.position - (Vector3)randomDirection * spawnDistance;
            Instantiate(skeletonPrefab, spawnPosition, Quaternion.identity);
        }
    }

    private bool IsPositionInCameraView(Vector3 position)
    {
        Vector3 viewportPoint = Camera.main.WorldToViewportPoint(position);
        return (viewportPoint.x > 0 && viewportPoint.x < 1 && viewportPoint.y > 0 && viewportPoint.y < 1);
    }
}